package com.qf.tast;

import com.event.util.EventUtil;
import com.qf.entity.Coupon;
import com.qf.entity.Msg;
import com.qf.service.CouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

@Component
public class TixingTimeTask {

    @Autowired
    private CouponService couponService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private EventUtil eventUtil;

    @Scheduled(cron = "0 50 * * * *")
    public void tixingTask(){
        System.out.println("午时已到:" + new Date());

        //获取当前时间
        Date now = new Date();
        String key = "tixing_" + new SimpleDateFormat("yyMMdd").format(now);
        double score = Double.valueOf(new SimpleDateFormat("HHmm").format(now));
        //去redis中找出对应时间范围的提醒消息
        Set<String> strSet = redisTemplate.opsForZSet().rangeByScore(key, score, score);
        //迭代set集合依次发送提醒消息
        for (String info : strSet) {
            String devid = info.split("-")[0];
            Integer cid = Integer.parseInt(info.split("-")[1]);
            Coupon coupon = couponService.getById(cid);
            //构建提醒消息，通知消息中心发送提醒消息
            Msg msg = new Msg()
                    .setType(2)
                    .setToDev(devid)
                    .setData("您所关注的《" + coupon.getSubject() + "》优惠券即将开抢，请放下屠刀！");

            //通过事件总线群发消息到消息中心集群
            eventUtil.publishEvent("tixing", msg);
        }
    }
}
